package com.ai.interceptor;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ai.aop.AuthorityAnnotation;
import com.ai.aop.FunctionType;
import com.ai.common.exception.BusinessException;
import com.ai.common.model.vo.BackOperatorVO;
import com.ai.model.edu.cms.backoperator.vo.MenuVO;
import com.ai.service.cms.user.BackendOperatorService;

/**
 * Class Name : CheckOperatorFunctionInterceptor<br>
 * 
 * Description : 校验是否有功能操作权限<br>
 * 
 * @author yangwb
 * @version $Revision$
 * @see
 *
 */
public class CheckOperatorFunctionInterceptor extends HandlerInterceptorAdapter {

    // 是否超级用户
    public static final int IS_SUPER_USER = 1;

    protected final Log log = LogFactory.getLog(getClass());

    @Resource
    private BackendOperatorService backendOperatorService;

    /**
     * Method Name : preHandle<br>
     * 
     * Description : 权限校验拦截器<br>
     * 
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     * @since
     * 
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod method = (HandlerMethod) handler;
        // 获取当前操作方法
        AuthorityAnnotation authorityAnnotation = method.getMethodAnnotation(AuthorityAnnotation.class);
        if (null == authorityAnnotation) {
            // 没有声明权限,放行
            return true;
        }
        // 获取登录信息
        BackOperatorVO backOperatorVO = (BackOperatorVO) request.getAttribute("backendOperatorVO");
        if (backOperatorVO == null) {
            BusinessException.throwMessage("未检测到登录信息，请先登录再试！");
        }
        // 判断是否超级用户
        if (backOperatorVO.getIsSuperUser().equals(IS_SUPER_USER)) {
            return true;
        }
        // 根据用户查询当前用户下的菜单 map key ：functionCode ; value:menuVo
        Map<String, MenuVO> menuMap = backendOperatorService.findMenuVOSById(backOperatorVO.getId());
        if (CollectionUtils.isEmpty(menuMap)) {
            BusinessException.throwMessage("您当前没有任何菜单访问权限，请联系管理员！");
        }
        FunctionType[] functionTypes = authorityAnnotation.functionType();
        for (FunctionType functionType : functionTypes) {
            // 当前用户拥有该菜单权限
            if (menuMap.get(functionType.getFunctionCode()) != null) {
                return true;
            } else {
                BusinessException.throwMessage("您没有当前菜单操作权限，请联系管理员！");
            }
        }
        return true;
    }
}
